package com.ren.article.listener;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.ren.article.constant.CachePrefix;
import com.ren.utils.canal.CanalBean;
import com.ren.utils.canal.CanalType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @ClassName: CanalMQListener
 * @Description: TODO
 * @Author: RZY
 * @DATE: 2022/7/17 9:13
 * @Version: v1.0
 */

@Component
@Slf4j
public class CanalMQListener {

    @Autowired
    CachePrefix cachePrefix;

    @RabbitListener(queues = "canal.queue.article.8004")
    public void CanalMessageHandler(Message message, Channel channel) {
        //获取消息体内容
        CanalBean canalBean = null;
        try {
            //序列化消息体
            canalBean = JSON.parseObject(new String(message.getBody(), StandardCharsets.UTF_8), CanalBean.class);
            log.info("来自队列 {} 的消息", 8001);
            log.info("收到canal消息： {}", canalBean);
            String tableName = canalBean.getTable();
            if(CachePrefix.isContainsTableName(tableName) && !canalBean.isDdl()) {
                //当为UPDATE时，更新缓存
                if(canalBean.getType().equals(CanalType.UPDATE)) cachePrefix.updateCache(tableName, canalBean);
                //当为DELETE时，删除缓存
                if(canalBean.getType().equals(CanalType.DELETE)) cachePrefix.deleteCache(tableName, canalBean);
            }
        } catch (Exception e) {
            log.info("canal消息处理失败: {}", canalBean);
            throw new RuntimeException(e);
        }

    }
}
